<template>
  <div class="login-container">
    <div class="left-container">
      <img src="../assets/bg.jpg" alt="login-image" class="login-image">
    </div>
    <div class="right-container">
      <el-form ref="loginForm" :model="loginForm" :rules="loginRules" class="login-form">
        <el-form-item prop="username" label="用户名" label-width="80px">
          <el-input v-model="loginForm.username" placeholder="请输入用户名" ></el-input>
        </el-form-item>

        <el-form-item prop="password" label="密码" label-width="80px">
          <el-input type="password" v-model="loginForm.password" placeholder="请输入密码"></el-input>
        </el-form-item>

        <el-form-item prop="captcha" label="验证码" label-width="80px">
          <el-input v-model="loginForm.captcha" placeholder="请输入验证码"></el-input>
          <span v-html="captchaImg" @click="refreshCaptcha"></span>
        </el-form-item>

        <el-form-item label-width="100px"> 
          <el-button type="primary" @click="handleSubmit">登录</el-button>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>

<script>
import { ElForm, ElFormItem, ElInput, ElButton, ElMessage } from 'element-plus';
import jsPDF from 'jspdf';
import axios from '../axios'

export default {
  components: {
    ElForm,
    ElFormItem,
    ElInput,
    ElButton
  },
  data() {
    return {
      loginForm: {
        username: '',
        password: '',
        captcha: ''
      },
      loginRules: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' }
        ],
        captcha: [
          { required: true, message: '请输入验证码', trigger: 'blur' }
        ]
      },
      captchaImg: ''
    };
  },
  methods: {
    async refreshCaptcha() {
      // 从后端获取验证码图片，添加时间戳以避免缓存
        // await axios.get(`./captcha?_=${new Date().getTime()}`)
        await axios.get('./captcha')
          .then(response => {
            this.captchaImg = response.data.data.svg
            // this.captchaImg = response.data.data.captchaSvg;
          })
    },

    handleSubmit() {
      this.$refs.loginForm.validate( (valid) => {
        if (valid) {
          // 提交登录表单，验证用户名、密码和验证码
          axios.post('./login', this.loginForm)
            .then(response => {
              console.log(response)
              if (response.data.success) {
                ElMessage.success(response.data.message);
                localStorage.setItem('token', response.data.token);
                this.$router.push('/home');
              } else {
                ElMessage.error(response.data.message);
                this.refreshCaptcha(); // 登录失败时刷新验证码
              }
            })
            .catch(error => {
              console.error('登录失败', error);
            });
        } else {
          return false;
        }
      });
    },

    generatePDF() {
      const pdf = new jsPDF();
      const formDataStr = `Name: ${this.formData.name}\nEmail: ${this.formData.email}`;
      pdf.text(formDataStr, 10, 10);
      pdf.save('form_data.pdf');
    }
  },

  mounted() {
    this.refreshCaptcha();
  }
};
</script>

<style>
.login-container {
  display: flex;
  height: 100vh;
}

.left-container {
  flex: 1;
}

.right-container {
  flex: 1;
  display: flex;
  justify-content: center;
  align-items: center;
}

.login-image {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.captcha-image {
  cursor: pointer;
}
</style>